package itsm.isperp.module.service.sparepart;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.module.entity.sparepart.SptSparepartChangeDetail;
import itsm.isperp.module.repository.sparepart.SptSparepartChangeDetailMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class SptSparepartChangeDetailService extends
		BaseService<SptSparepartChangeDetail> {

	@Autowired
	protected SptSparepartChangeDetailMapper sptSparepartChangeDetailMapper;

	@Override
	public SptSparepartChangeDetailMapper getRepository() {
		return this.sptSparepartChangeDetailMapper;
	}

	public void batchSave(String relationId, String[] sparepartIds,String typeKey) {

		String sql = "INSERT INTO spt_sparepart_change_detail(id,relation_id,spt_sparepart_id,type_key)VALUES(?,?,?,?)";

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		List<Object[]> list = new ArrayList<>();

		if (sparepartIds != null && sparepartIds.length > 0) {
			for (String m : sparepartIds) {
				Object[] arg = new Object[4];
				arg[0] = HibernateUUIDGenerator.generate();
				arg[1] = relationId;
				arg[2] = m;
				arg[3]=typeKey;

				list.add(arg);
			}

			jdbcTemplate.batchUpdate(sql, list);
		}

	}

	public List<Map<String, Object>> findAllDetailByRelationId(String relationId) {
		return this.getRepository().findAllDetailByRelationId(relationId);
	}

	public void deleteByRelationId(String relationId) {

		String sql = "DELETE FROM  spt_sparepart_change_detail WHERE relation_id=?";

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		jdbcTemplate.update(sql, relationId);
	}
	
	public List<Map<String, Object>> listStore(String relationId) {
		String sql = "SELECT IFNULL(location_name,'其他') AS location_name,c.name as conf_category_name,COUNT(1) AS quantity,specification,status FROM conf_ci a " 
                   +" LEFT JOIN conf_category c ON a.conf_category_id=c.id where a.are_company=1 and  exists(SELECT 1 FROM spt_sparepart_change_detail e WHERE c.id=e.conf_category_id and a.specification=e.specification and spt_sparepart_id='"+relationId+"')"
                   +" GROUP BY location_name,c.name,specification,status";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		return jdbcTemplate.queryForList(sql);
	}
	
	

}